﻿using System;

namespace Basmus.Conel
{
    public class EntityBinder : IBinder
    {
        public Binding Bind(Type containerType, Type elementType)
        {
            if (containerType == elementType)
            {
                return Bind(containerType);
            }
            return null;
        }

        public Binding Bind(Type containerType)
        {
            var valueTypeCheck = containerType == typeof (int) ||
                                 containerType == typeof (bool) ||
                                 containerType == typeof (Guid) ||
                                 containerType.IsEnum ||
                                 Nullable.GetUnderlyingType(containerType) != null;
            if (valueTypeCheck)
            {
                return CreateValueTypeEntityBinding(containerType);
            }
            if (containerType == typeof (string))
            {
                return new StringBinding();
            }
            return null;
        }

        private static Binding CreateValueTypeEntityBinding(Type elementType)
        {
            var bindingType = typeof(ValueTypeEntityBinding<>).MakeGenericType(elementType);
            var binding = (Binding)Activator.CreateInstance(bindingType);
            return binding;
        }
    }
}
